import Vue from "vue";
import { getToken, setToken, removeToken } from "@/utils/auth";
import Cookies from "js-cookie";
import App from "./App";
import store from "@/store";
import router from "@/router";
import plugins from "./plugins"; // plugins

// import './assets/styles/element-variables.scss';
import "element-ui/lib/theme-chalk/index.css";
import "@/assets/styles/index.scss"; // global css
import "@/assets/styles/ruoyi.scss"; // ruoyi css
import "normalize.css/normalize.css"; // a modern alternative to CSS resets
import "viewerjs/dist/viewer.css";
// 引入样式
import "vue-easytable/libs/theme-default/index.css";
import "@/assets/icons"; // icon
import "@/permission"; // permission control

import "@/utils/sticky";
import "@/utils/mainOperation/mainDirective";
import MainComponent from "@/utils/mainOperation/mainComponent";
import "@/utils/mainOperation/mainFn";
let instance = null;
import { updateTheme } from '@/utils/theme'
// import VueNativeSock from 'vue-native-websocket';
function render(props = {}) {
  const { container } = props;

  const mountEl = container ? container.querySelector("#app") : document.querySelector("#app");
  instance = new Vue({
    router,
    store,
    created() {
      window.Vue = Vue;
    },
    render: (h) => h(App),
  });
  if (mountEl) {
    instance.$mount(mountEl);
  } else {
    console.error("找不到挂载节点 #app");
  }
}
 
// 非微前端场景下会挂载 __POWERED_BY_WUJIE__
if (!window.__POWERED_BY_WUJIE__) {
  render();
}
// 确保生命周期函数同时支持 ESM 和 UMD 格式导出
if (window.__POWERED_BY_WUJIE__) {
  window.__WUJIE_MOUNT = mount;
  window.__WUJIE_UNMOUNT = unmount;
  window.__WUJIE_BOOTSTRAP = bootstrap;
}
// 提供给无界使用的生命周期函数
export async function bootstrap() {
  console.log("[vue] vue app bootstraped");
}

async function unmount() {
 // 清理事件监听
 if (window.$wujie && window.$wujie.bus) {
  window.$wujie.bus.$off("sub-route-change");
}

// 销毁实例
if (instance) {
  instance.$destroy();
  instance = null;
}
}
export async function mount(props) {
  render(props);
  if (window.$wujie.props) {
    const token = window.$wujie.props.token;
    setToken(token());
    if(window.$wujie.props.parentRouter){
      console.log("🚀 ~ file: main.js:79 ~ window.$wujie.props.parentRouter:", window.$wujie.props.parentRouter.currentRoute)
       router.replace(window.$wujie.props.parentRouter.currentRoute.path);
    }
  }
   // 在子应用的入口文件或主题配置文件中
if (window.$wujie && window.$wujie.props && window.$wujie.props.theme) {
  const { colorPrimary, mode } = window.$wujie.props.theme;
  updateTheme(colorPrimary)
  
  // 设置 Element Plus 的主题色
  document.documentElement.style.setProperty('--el-color-primary', colorPrimary);
  
  // 如果需要设置暗色/亮色模式
  if (mode === 'dark') {
    document.documentElement.classList.add('dark');
    // 或者使用 Element Plus 的暗色模式
    // document.documentElement.setAttribute('data-theme', 'dark');
  }
}
  // 先移除可能存在的旧监听器，避免重复
  window.$wujie.bus.$off("sub-route-change");
  
  // 在mount中重新注册事件监听
  window.$wujie.bus.$on("sub-route-change", (path) => {
    console.log("子应用接收到路由变更事件:", path);
    Vue.prototype.$message = wrapMessage(window.$wujie.props.ElMessage);
    if (path && path !== router.currentRoute.fullPath) {
      router.replace(path);
    }
  });
  
 
  window.$store = store;
}
function wrapMessage(ElMessage) {
  return function (msg) {
    if (typeof msg === "string") {
      ElMessage({ message: msg });
    } else {
      ElMessage(msg);
    }
  };
}
 
Vue.prototype.msgSuccess = function (msg) {
  this.$message({ showClose: true, message: msg, type: "success" });
};

Vue.prototype.msgError = function (msg) {
  this.$message({ showClose: true, message: msg, type: "error" });
};

Vue.prototype.msgInfo = function (msg) {
  this.$message.info(msg);
};

Vue.prototype.msgWarning = function (msg) {
  this.$message.warning(msg);
};

Vue.prototype.$ELEMENT = { size: Cookies.get("size") || "mini", zIndex: 3000 };
Vue.config.productionTip = false;

Vue.use(plugins);
Vue.use(MainComponent);

// Vue.use(VueNativeSock, WS, {
//   // 启用Vuex集成,store的值为你的vuex
//   store: store,
//   // 数据发送/接收使用使用json格式
//   format: 'json',
//   // 开启自动重连
//   reconnection: true,
//   // 尝试重连的次数
//   reconnectionAttempts: 5,
//   // 重连间隔时间
//   reconnectionDelay: 3000,
//   // 将数据进行序列化，由于启用了json格式的数据传输这里需要进行重写
//   passToStoreHandler: function (eventName, event) {
//     if (!eventName.startsWith('SOCKET_')) {
//       return;
//     }
//
//     let method = 'commit';
//     let target = eventName.toUpperCase();
//     let msg = event;
//     if (this.format === 'json' && event.data) {
//       msg = JSON.parse(event.data);
//       /* if (msg.mutation) {
//         target = [msg.namespace || '', msg.mutation].filter((e) => !!e).join('/');
//       } else if (msg.action) {
//         method = 'dispatch';
//         target = [msg.namespace || '', msg.action].filter((e) => !!e).join('/');
//       }*/
//     }
//     this.store[method](target, msg);
//     this.store.state.socket.message = msg;
//   },
// });

// new Vue({
//   el: "#app",
//   router,
//   store,
//   created() {
//     window.Vue = Vue
//   },
//   render: h => h(App)
// })
